/*


 */

package jas.http.response;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.util.HashMap;
import java.util.Map;

/**
 *
 *
 */
public class HttpResponse {

    
    private ResponseBody body;
    private ResponseCode code;
    private Map<String, String> headers = new HashMap<String, String>();
    
    public HttpResponse() {
    }
    
    public void setBody(ResponseBody body) {
        this.body = body;
    }
    
    public void setHeader(String header, String value) {
        headers.put(header, value);
    }

    public ResponseCode getCode() {
        return code;
    }

    public void setCode(ResponseCode code) {
        this.code = code;
    }
    
    public void print(OutputStream output) throws IOException {
        output.write( (getHeaderString() + "\r\n").getBytes() );
        body.print(output);
    }
    
    public String getHeaderString() {
        String s = "HTTP/1.0 " + code.getCodeNumber() + " " + code.getName() + "\r\n";
        for (String header : headers.keySet()) {
            String value = headers.get(header);
            s += header + ": " + value + "\r\n";
        }
        return s;
    }
    
    @Override
    public String toString() {
        return getHeaderString();
    }

    public long getContentLength() {
        return body.getContentLength();
    }

    public String getContentType() {
        return body.getContentType();
    }

    public String getContentEncoding() {
        return body.getContentEncoding();
    }
    
    public static HttpResponse createStandardResponse(ResponseCode code) {
        HttpResponse response = new HttpResponse();
        response.setBody(new StringResponseBody(code.toString()));
        response.setCode(code);
        return response;
    }
    
    public String getBodyAsString() throws IOException {
        ByteArrayOutputStream buffer = new ByteArrayOutputStream();
        body.print(buffer);
        return buffer.toString("UTF-8");
    }
}

